package com.gxc.service.impl;

import com.alibaba.fastjson.JSON;
import com.gxc.dao.jpa.UserRepository;
import com.gxc.entity.User;
import com.gxc.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author GongXincheng
 * @since 2019-07-30 16:05
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserRepository userRepository;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public List<User> addEg(List<User> userList) {
        return userRepository.saveAll(userList);
    }

    @Override
    public User findById(Integer id) {
        User user;
        ValueOperations opsForValue = stringRedisTemplate.opsForValue();
        String userJson = (String) opsForValue.get(id + "");
        if (userJson == null) {
            user = userRepository.findById(id).get();
            opsForValue.set(id + "", JSON.toJSONString(user), 10, TimeUnit.MINUTES);
        } else {
            stringRedisTemplate.expire(id + "", 10, TimeUnit.MINUTES);
            user = JSON.parseObject(userJson, User.class);
        }
        return user;
    }

    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

}
